package it.biffi.jirc.bot.main;

import it.biffi.jirc.bot.BotException;
import it.biffi.jirc.bot.service.Service;
import it.biffi.jirc.bot.service.ServiceCallback;
import it.biffi.jirc.bot.util.XDCCPopupDecoder;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	/* /msg SUN|SERIETV-NEWS|02 xdcc send #846 */
	// public static ServiceConfig config = new ServiceConfig("irc.uragano.org",
	// "sunshine", "SUN|SERIETV-NEWS|01", "924");

	// public static ServiceConfig config = new
	// ServiceConfig("irc.devilirc.org",
	// "paprika", "PRK|SERIETV-NEWS|04", "924");

	public static void main(String[] args) throws BotException {
		ServiceConfig config = null;
		// /msg SUN|SERIETV-NEWS|26 xdcc send #102
		if (args.length == 2) {
			boolean ok = args[0].equals("--file");
			if (!ok) {
				printOutGuide();
				return;
			}
			config = buildConfigFromFile(args[1]);
		}
		if (config == null && args.length != 8) {
			printOutGuide();
			return;
		}
		if (config == null) {
			config = buildConfig(args);
		}
		Service serv = new Service();
		ServiceCallback c = new Callback(config, serv);
		serv.setCallback(c);
		System.out.println("starting service with: " + config);
		serv.start(config.getServer(), config.getChannel(), config.getBot(),
				config.getPacket(), config.getTargetFolder(), 15000);

	}

	private static ServiceConfig buildConfigFromFile(String file) {

		String executionPath = System.getProperty("user.dir");
		executionPath = executionPath.replace("\\", "/");
		String sFile = executionPath + "/" + file;
		System.out.println(sFile);
		File f = new File(sFile);
		StringBuffer buffer = new StringBuffer();
		try {
			FileInputStream in = new FileInputStream(f);
			BufferedInputStream buffIn = new BufferedInputStream(in);
			// FileReader reader = new FileReader(f);
			// reader.re
			Scanner sc = new Scanner(f);

			while (sc.hasNext()) {
				String token = sc.next();
				// System.out.println(token);
				buffer.append(token + " ");
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		String[] options = XDCCPopupDecoder.decode(buffer.toString());
		ServiceConfig config = new ServiceConfig(options[0], options[1],
				options[2], options[3]);
		config.setTargetFolder(executionPath);
		if (config.getServer().isEmpty()) {
			config.setServer("Tornado.uragano.org");
		}
		return config;

	}

	private static void printOutGuide() {
		System.out.println("Usage: ");
		System.out
				.println("For xdcc formatted string from popup site use only this:");
		System.out.println("--file <inputFile>");
		System.out
				.println("Or use indivudal parameter trough these command option:");
		System.out.println("-s <server>");
		System.out.println("-c <channelname>");
		System.out.println("-b <botname>");
		System.out.println("-p <packetNumber>");
	}

	private static ServiceConfig buildConfig(String args[]) {
		ServiceConfig conf = new ServiceConfig("", "", "", "");
		List<String> tokens = new ArrayList<String>();
		for (int i = 0; i < args.length; i++) {
			int current = i;
			if (args[i].equals("-s")) {
				conf.setServer(args[current + 1]);
			}
			if (args[i].equals("-c")) {
				conf.setChannel(args[current + 1]);
			}
			if (args[i].equals("-b")) {
				conf.setBot(args[current + 1]);
			}
			if (args[i].equals("-p")) {
				conf.setPacket(args[current + 1]);
			}
		}
		String executionPath = System.getProperty("user.dir");
		executionPath = executionPath.replace("\\", "/");
		conf.setTargetFolder(executionPath);

		return conf;
	}

	private static class ServiceConfig {
		private String server;
		private String channel;
		private String bot;
		private String packet;
		private String targetFolder;

		public ServiceConfig(String server, String channel, String bot,
				String packet) {
			this.bot = bot;
			;
			this.channel = channel;
			this.packet = packet;
			this.server = server;
		}

		public String getServer() {
			return server;
		}

		public void setServer(String server) {
			this.server = server;
		}

		public String getChannel() {
			return channel;
		}

		public void setChannel(String channel) {
			this.channel = channel;
		}

		public String getBot() {
			return bot;
		}

		public void setBot(String bot) {
			this.bot = bot;
		}

		public String getPacket() {
			return packet;
		}

		public void setPacket(String packet) {
			this.packet = packet;
		}

		@Override
		public String toString() {
			return "ServiceConfig [server=" + server + ", channel=" + channel
					+ ", bot=" + bot + ", packet=" + packet + "]";
		}

		public String getTargetFolder() {
			return targetFolder;
		}

		public void setTargetFolder(String targetFolder) {
			this.targetFolder = targetFolder;
		}

	}

	private static class Callback implements ServiceCallback {

		private Service s;

		private int retry;

		private ServiceConfig config;

		public Callback(ServiceConfig config, Service s) {
			this.s = s;
			this.config = config;
		}

		@Override
		public void onStarted() {
			System.out.println("download started: " + config);

		}

		@Override
		public void onProgress(int percent) {
			System.out.println("" + percent);

		}

		@Override
		public void onInterrupeted() {
			long timeout = 60000;
			retry++;
			if (retry == 5) {
				timeout = 120000;
				retry = 0;
			}
			System.out.println("download interrupetd not finished restart pls");
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			s.stop();

			try {
				Thread.sleep(1000);
				s.start(config.getServer(), config.getChannel(),
						config.getBot(), config.getPacket(),
						config.getTargetFolder(), timeout);
			} catch (BotException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void onFinish() {
			s.stop();

		}

		@Override
		public void onConnected() {
			System.out.println("connected");

		}

		@Override
		public void onTransferRateChage(int rate) {
			// TODO Auto-generated method stub

		}
	}
}
